﻿using System;
using WeDonekRpc.ApiGateway;
using WeDonekRpc.ApiGateway.Interface;
using WeDonekRpc.ApiGateway.Model;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.HttpApiGateway.Interface;

namespace WeDonekRpc.HttpApiGateway
{
    internal class ApiGatewayService
    {
        private static IApiDocModular _ApiDoc;
        private static readonly IHttpConfig _Config = new Config.HttpConfig();
        public static IHttpConfig Config => _Config;

        public static void Init ()
        {
            GatewayServer.LoadEv += GatewayServer_Load;
            GatewayServer.InitEv += GatewayServer_InitEv;
            GatewayServer.Starting += GatewayServer_Starting;
            GatewayServer.Closeing += GatewayServer_Closeing;
        }

        private static void GatewayServer_InitEv (IIocService obj)
        {
            _ApiDoc = obj.Resolve<IApiDocModular>();
        }

        private static void GatewayServer_Load (IGatewayOption obj)
        {
            _ = obj.IocBuffer.RegisterInstance<IHttpConfig>(_Config);
            obj.RegModular(new GatewayModular());
        }

        private static void GatewayServer_Closeing ()
        {
            HttpService.HttpService.StopService();
        }

        private static void GatewayServer_Starting ()
        {
            ApiPlugInService.Init();
            HttpService.HttpService.RegService(Config.Url);
        }

        internal static string GetApiShow (Uri uri)
        {
            if (_ApiDoc == null)
            {
                return string.Empty;
            }
            return _ApiDoc.GetApiShow(uri);
        }

        internal static void RegModular (string name, Type source)
        {
            _ApiDoc?.RegModular(name, source, _Config.Url);
        }
        internal static void RegApi (ApiFuncBody api)
        {
            _ApiDoc?.RegApi(api);
        }
    }
}
